package com.jinyou.chengfengshop.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.jinyou.chengfengshop.Constant.AppUrl;
import com.jinyou.chengfengshop.R;
import com.jinyou.chengfengshop.adapter.AddOrderPhotoAdapter;
import com.jinyou.chengfengshop.bean.UploadImageBean;
import com.jinyou.chengfengshop.bean.infosBean;
import com.jinyou.chengfengshop.utils.BaseRequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.OkHttpClient;

/**
 * Created by zhuzhiqiang on 2018/9/23.
 */

public class AddOrderPhotoActivity extends AppCompatActivity {
    private List<infosBean> ifb;
    private AddOrderPhotoAdapter mAdapter;
    private RecyclerView add_list;

    private final OkHttpClient client = new OkHttpClient();


    public static AddOrderPhotoActivity instanece;
    private Uri imageUri;
    public static File tempFile;
    private String mCurrentPhotoPath;
    private String orderJson = "";
    String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE
    };

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 2;

    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();
    public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    private Uri photoUri;
    private String picPath;
    private Intent lastIntent ;
    public static final String KEY_PHOTO_PATH = "photo_path";

    private long routeAddrId;
    private String routeId;
    private String filename;
    public static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    public static final int CROP_PHOTO = 2;
  @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addorder_photo);
        instanece = this;

        ifb = (List<infosBean>) getIntent().getSerializableExtra("INFOB");
        add_list = (RecyclerView)findViewById(R.id.add_list);
        GridLayoutManager layoutManage = new GridLayoutManager(this, 1);
        add_list.setLayoutManager(layoutManage);
        mAdapter = new AddOrderPhotoAdapter(getApplicationContext(),ifb);
        add_list.setAdapter(mAdapter);
    }









    public void openCamera(long id,String rou) {
        routeAddrId = id;
        routeId = rou;

        //获取系統版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyyMMddHHmmss");
            filename = timeStampFormat.format(new Date());
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    filename + ".png");
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                //检查是否有存储权限，以免崩溃
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    reqPermission();
                    Toast.makeText(this,"请开启存储权限",Toast.LENGTH_SHORT).show();
                    return;
                }
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                imageUri = getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /*
    * 判断sdcard是否被挂载
    */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }


    //获取拍照储存权限
    private void reqPermission(){
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(AddOrderPhotoActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了


            //openCamera(routeAddrId,routeId);

            //Toast.makeText(AddOrderPhotoActivity.this,"已经授权",Toast.LENGTH_LONG).show();
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(AddOrderPhotoActivity.this, permissions, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
        }
    }



    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(),filename+".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                //BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            //BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps==null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTO_REQUEST_CAREMA:
                if (resultCode == RESULT_OK) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            addOrderD(Environment.getExternalStorageDirectory()+"/"+filename+".png");
                        }
                    }).start();
                }
                break;
            case CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                                .openInputStream(imageUri));


                        //photo_img.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

   //商户发单
    private void addOrderD(String btm){
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        String tocken = sh.getString("tocken","");
        orderJson = "[{\"routeAddrId\":"+routeId+",\"routeId\":"+routeAddrId+"}]";

        ShopImageUpload(tocken,btm,orderJson,new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                UploadImageBean bean = new Gson().fromJson(responseInfo.result, UploadImageBean.class);
                if (1 == bean.getStatus()) {
                    Toast.makeText(getApplicationContext(),"发单成功", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(getApplicationContext(),bean.getError(), Toast.LENGTH_SHORT).show();
                }
                //Toast.makeText(getApplicationContext(), responseInfo.toString(), Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();

            }
        });

    }

    //上传图片
    private void ShopImageUpload(String token, String filepath, String orderJson,RequestCallBack<String> callback) {
        File file = new File(filepath);
        Uri uri = Uri.fromFile(file);
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);

            HttpUtils httpUtils = new HttpUtils(10000);
            RequestParams params = new BaseRequestParams().getParams();
            if (file != null) {
                params.addBodyParameter("token", token);
                params.addBodyParameter("sysCustomer", "o2o-chengfeng");
                params.addBodyParameter("orders",orderJson);
                params.addBodyParameter("file01", compressImage(bitmap),"image/png");
            }
            httpUtils.send(HttpMethod.POST, AppUrl.ORDER_ADD, params, callback);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
